<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" style="width: 240px">
          <el-option v-for="dict in sys_payment_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="商家id" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入商家id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>-->
<!--      <el-form-item label="应付金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入应付金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="Goods" @click="mergeCheckout">合并付款</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="微信昵称" align="center" prop="wxUser.nickname" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_payment_type" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="游戏类型" align="center" prop="gameType">
        <template #default="scope">
          <dict-tag :options="sys_game_type" :value="scope.row.gameType" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="amount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleEnd(scope.row)" v-hasPermi="['system:records:edit']" v-if="scope.row.status ==='0'">结束游玩</el-button>
          <el-button link type="primary" icon="Edit" @click="handlePayment(scope.row)" v-hasPermi="['system:records:edit']" v-if="scope.row.status ==='1'">完成付款</el-button>
          <el-button link type="primary" icon="Delete" @click="handleVip(scope.row)" v-hasPermi="['system:records:edit']" v-if="scope.row.status ==='1'">会员扣款</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- vip扣款对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form :model="vipQueryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="手机尾号" prop="phone">
          <el-input
              v-model="vipQueryParams.phone"
              placeholder="请输入手机尾号"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchVip">搜索</el-button>
          <div style="display: inline-block;margin-left: 100px;font-size: 25px; color: red"> 应付总金额：{{totalAmount}}</div>
        </el-form-item>
      </el-form>
      <el-table v-loading="viploading" :data="vipList">

        <el-table-column label="会员id" align="center" prop="vipId" />
        <el-table-column label="会员名称" align="center" prop="name" />
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="余额" align="center" prop="balance" />
        <el-table-column label="会员类型" align="center" prop="type" >
          <template #default="scope">
            <dict-tag :options="sys_vip_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.balance > totalAmount" link type="primary" icon="Edit" @click="handleCheckout(scope.row)" v-hasPermi="['system:vip:edit']">扣款</el-button>
            <div v-else>余额不足</div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">已完成付款</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Records">
import { listRecords, getRecords, delRecords, addRecords, updateRecords, updateVipAndRecords, endRecords } from "@/api/system/records"
import { listVip, updateVip } from "@/api/system/vip"
import ElMessage, { ElMessageBox } from 'element-plus'  // Vue 3 + Element Plus
const { proxy } = getCurrentInstance()
const { sys_game_type } = proxy.useDict("sys_game_type")
const { sys_payment_type } = proxy.useDict("sys_payment_type")
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")
const { sys_vip_type } = proxy.useDict("sys_vip_type")
const recordsList = ref([])
const vipList = ref([])
const open = ref(false)
const loading = ref(true)
const vipLoading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const vipTotal = ref(0)
const title = ref("")
const totalAmount = ref(0)
const currentCheckoutRecordList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wxId: null,
    deptId: null,
    gameType: null,
    startTime: new Date().toISOString().split('T')[0], // 格式化为 YYYY-MM-DD
    endTime: null,
    amount: null,
    status: '0'
  },
  vipQueryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: '',
    status: '0'
  },

})

const { vipQueryParams, queryParams, form, rules } = toRefs(data)

/** 查询游戏记录列表 */
function getList() {
  loading.value = true
  listRecords(queryParams.value).then(response => {
    console.log(response.rows)
    recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 结束游玩操作 */
function handleEnd(row) {
  ElMessageBox.confirm('确定要标记为结束游玩吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 用户点击"确定"，调用 API 更新状态
    let record = {id: row.id}
    endRecords(record).then(response => {
      getList()  // 假设你有一个 getList() 方法加载数据
      if (response.code === 200) {
        ElMessage.success('付款状态更新成功')
      } else {
        ElMessage.error(response.msg || '更新失败')
      }
    }).catch(error => {
      ElMessage.error('操作失败：' + error.message)
    })
  }).catch(() => {
    // 用户点击"取消"，什么都不做
  })
}

/** 完成付款操作 */
function handlePayment(row) {
  ElMessageBox.confirm('确定要标记为已完成付款吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 用户点击"确定"，调用 API 更新状态
    let record = {id: row.id, status: 2}
    updateRecords(record).then(response => {
      getList()  // 假设你有一个 getList() 方法加载数据
      if (response.code === 200) {
        ElMessage.success('付款状态更新成功')
        // 刷新列表数据（根据你的实际代码调整）
        //getList()  // 假设你有一个 getList() 方法加载数据
      } else {
        ElMessage.error(response.msg || '更新失败')
      }
    }).catch(error => {
      ElMessage.error('操作失败：' + error.message)
    })
  }).catch(() => {
    // 用户点击"取消"，什么都不做
  })
}

/** 打开vip列表对话框 */
function handleVip(row) {
    totalAmount.value = row.amount // 当前结账总金额
    currentCheckoutRecordList.value = []
    currentCheckoutRecordList.value.push(row.id)
    //console.log(currentCheckoutRecordList.value)
    title.value = "会员扣款"
    open.value = true
    vipLoading.value = true
    listVip(vipQueryParams.value).then(response => {
      vipList.value = response.rows
      vipTotal.value = response.total
      vipLoading.value = false
    })
}

/** vip扣款操作 */
function handleCheckout(row) {
  //计算新的余额
  const nb = row.balance - totalAmount.value
      // 构造请求数据（VIP余额 + 要更新的records）
  const requestData = {
    vipId: row.vipId,
    balance: nb,
    recordIdList: currentCheckoutRecordList.value, //选中结算的游戏记录数组
  };
  // 发送单次请求
  updateVipAndRecords(requestData)
      .then(() => {
        open.value = false
        getList();  // 刷新数据
        proxy.$modal.msgSuccess("手机尾号："+row.phone+"，会员扣款成功! 剩余"+nb+"元", { duration: 5000 });
      })
      .catch(error => {
        proxy.$modal.msgError("扣款失败：" + error.message);
      });
}

/** 合并扣款 */
function mergeCheckout(){
  if(queryParams.value.status != '1'){
    proxy.$modal.msgWarning("请在未付款列表中选择");
    return
  }
  console.log(ids.value)
  currentCheckoutRecordList.value = ids.value
  //计算总金额
  totalAmount.value = 0
  recordsList.value.forEach((item) => {
    if(currentCheckoutRecordList.value.includes(item.id)){
      totalAmount.value += item.amount
    }
  })
  title.value = "合并扣款"
  open.value = true
  vipLoading.value = true
  listVip(vipQueryParams.value).then(response => {
    vipList.value = response.rows
    vipTotal.value = response.total
    vipLoading.value = false
  })
}

/** 查询vip */
function searchVip() {
  vipLoading.value = true
  listVip(vipQueryParams.value).then(response => {
    vipList.value = response.rows
    vipTotal.value = response.total
    vipLoading.value = false
  })
}

/** 合并正常扫码付款 */
function submitForm() {
  //直接修改多个游戏记录状态
  // 构造请求数据（VIP余额 + 要更新的records）
  const requestData = {
    vipId: 0,
    balance: null, // 计算新余额
    recordIdList: currentCheckoutRecordList.value, //选中结算的游戏记录数组
  };
  // 发送单次请求
  updateVipAndRecords(requestData)
      .then(() => {
        open.value = false
        getList();  // 刷新数据
        proxy.$modal.msgSuccess("付款状态更新成功");
      })
      .catch(error => {
        proxy.$modal.msgError("付款状态更失败：" + error.message);
      });
}
getList()
</script>

